<template>
  <div class="app-container">
    <!--查询条件开始-->
     <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="所属部门" prop="deptId">
        <el-select
          v-model="queryParams.deptId"
          placeholder="请选择部门"
          clearable
          size="small"
          style="width:240px"
        >
          <el-option
            v-for="dict in deptOptions"
            :key="dict.deptId"
            :label="dict.deptName"
            :value="dict.deptId"
          />
        </el-select></el-form-item>
      <el-form-item label="用户姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户姓名"
          clearable
          size="small"
          style="width:240px"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          size="small"
          style="width:240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="可用状态"
          clearable
          size="small"
          style="width:240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width:240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholde="开始日期"
          end-placeholde="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--查询条件结束-->

    <!--表头按钮开始-->
    <el-row :gutter="10" style="margin-bottom: 8px;">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleResetPwd">重置密码</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-show="showRoleButton" type="warning" icon="el-icon-s-custom" size="mini" :disabled="single" @click="handleSelectRole">分配角色</el-button>
      </el-col>
    </el-row>
    <!--表头按钮结束-->

    <!--表格数据开始-->
    <el-table v-loading="loading" border :data="userTableList" @selection-change="handleSelectionChange">
      <el-table-column  type="selection" width="55" align="center" />
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="邮箱">
              <span>{{ props.row.email }}</span>
            </el-form-item>
            <el-form-item label="毕业学校">
              <span>{{ props.row.strong }}</span>
            </el-form-item>
            <el-form-item label="民族">
              <span>{{ props.row.honor }}</span>
            </el-form-item>
            <el-form-item label="身份证号码">
              <span>{{ props.row.introduction }}</span>
            </el-form-item>
            <el-form-item label="家庭联系">
              <span>{{ props.row.familyPhone }}</span>
            </el-form-item>
            <el-form-item label="QQ号码">
              <span>{{ props.row.qq }}</span>
            </el-form-item>
            <el-form-item label="民族">
              <span>{{ props.row.introduction }}</span>
            </el-form-item>
             <el-form-item label="手机号码【登陆身份】">
              <span>{{ props.row.phone }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="用户姓名" align="center" prop="userName" />
      <el-table-column label="部门" align="center" prop="deptId" :formatter="deptFormatter" />
      <el-table-column label="性别" align="center" prop="sex" :formatter="sexFormatter" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="是否排班" align="center" prop="schedulingFlag"  >
          <template slot-scope="scope">
            <el-tag :type="scope.row.schedulingFlag ==='0'?'success':'danger'">
                {{scope.row.schedulingFlag ==='0'?'是':'否'}}
            </el-tag>
          </template>
      </el-table-column>
      <el-table-column label="任职" prop="userRank" align="center" :formatter="userRankFormatter" />
      <el-table-column label="背景" prop="background" align="center" :formatter="backgroundFormatter" />
      <el-table-column label="校区" prop="campus" align="center" :formatter="campusFormatter" />
      <el-table-column label="状态" prop="status" align="center" :formatter="statusFormatter" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="200" />
      <el-table-column label="操作" align="center" width="250">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-if="scope.row.userId!=1" type="text" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          <el-button v-if="scope.row.userId!=1" type="text" icon="el-icon-thumb" size="mini" @click="handleSelectRole(scope.row)">分配角色</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--表格数据结束-->

    <!--分页插件开始-->
    <el-pagination
      v-show="total>0"
      :current-page="queryParams.pageNum"
      :page-sizes="[5, 10, 20, 30]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!--分页插件结束-->

    <!--添加修改弹出层开始-->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      center
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="userName">
              <el-input v-model="form.userName" style="width:240px" placeholder="请输入用户名称" clearable size="small" />
            </el-form-item></el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" style="width:240px" placeholder="请输入手机号，作为登陆凭证" clearable size="small" />
            </el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <el-select
                v-model="form.deptId"
                placeholder="所属部门"
                clearable
                size="small"
                style="width:240px"
              >
                <el-option
                  v-for="d in deptOptions"
                  :key="d.deptId"
                  :label="d.deptName"
                  :value="d.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任职" prop="userRank">
              <el-select
                v-model="form.userRank"
                placeholder="用户任职"
                clearable
                size="small"
                style="width:240px"
              >
                <el-option
                  v-for="d in userRankOptions"
                  :key="d.dictValue"
                  :label="d.dictLabel"
                  :value="d.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="form.age" clearable size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="背景" prop="background">
              <el-select
                v-model="form.background"
                placeholder="学历"
                clearable
                size="small"
                style="width:240px"
              >
                <el-option
                  v-for="d in backgroundOptions"
                  :key="d.dictValue"
                  :label="d.dictLabel"
                  :value="d.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio
                  v-for="d in sexOptions"
                  :key="d.dictValue"
                  :label="d.dictValue"
                  :value="d.dictValue"
                >{{ d.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                  :value="dict.dictValue"
                >{{ dict.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否参与排班" prop="schedulingFlag">
              <el-radio-group v-model="form.schedulingFlag">
                <el-radio
                  v-for="d in schedulingFlagOptions"
                  :key="d.dictValue"
                  :label="d.dictValue"
                  :value="d.dictValue"
                >{{ d.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" style="width:240px" placeholder="请输入用户邮箱" clearable size="small" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="毕业学校" prop="strong">
              <el-input v-model="form.strong"  placeholder="请输入用户毕业学校" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="民族" prop="honor">
              <el-input v-model="form.honor"  placeholder="请输入用户民族" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号码" prop="introduction">
              <el-input v-model="form.introduction"  placeholder="请输入用户身份证号码" />
            </el-form-item>
          </el-col>
           <el-col :span="12">
            <el-form-item label="所属校区" prop="campus">
              <el-select
                v-model="form.campus"
                placeholder="所属校区"
                clearable
                size="small"
                style="width:240px"
              >
                <el-option
                  v-for="d in campusOptions"
                   :key="d.dictValue"
                  :label="d.dictLabel"
                  :value="d.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </el-dialog>

    <!--添加修改弹出层失败-->
     <!-- 分配角色的弹出层开始 -->
    <el-dialog
      :title="title"
      :visible.sync="selectRoleOpen"
      width="900px"
      center
      append-to-body
    >
      <el-table
        v-loading="loading"
        ref="roleListTable"
        border
        :data="roleTableList"
        @selection-change="handleRoleTableSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="角色ID" align="center" prop="roleId" />
        <el-table-column label="角色名称" align="center" prop="roleName" />
        <el-table-column label="权限编码" align="center" prop="roleCode" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSaveRoleUserSubmit">确 定</el-button>
        <el-button @click="cancelRoleUser">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的弹出层结束 -->

  </div>
</template>
<script>
import {saveUserRole,listUserForPage,addUser,deleteUserByIds,updateUser,getUserById,resetPwd,getRoleIdsByUserId} from '@/api/system/user'
import {selectAllDept} from '@/api/system/dept'
import {selectAllRoles} from '@/api/system/role'
export default {
    data(){
      return{
        //分配角色是否显示
        selectRoleOpen:false,
        //查询所有角色信息
        roleTableList:[],
        //分配角色Id合集
        roleSelectionIds:[],
        //分配角色当前选中的用户
        roleUserId:'',
        //弹出层标题
        title:'',
        //时间
        dateRange:[],

        studentClassOptions:[],
        readingStateOptions:[],
        //状态数据字典
        statusOptions:[],
        //性别数据字典
        sexOptions:[],
        //用户任职数据字典
        userRankOptions:[],
        //用户背景数据字典
        backgroundOptions:[],
        //所有可用部门信息
        deptOptions:[],
        campusOptions:[],
        //排班状态
        schedulingFlagOptions:[],
        //查询参数
        queryParams:{
            pageNum:1
            ,pageSize:10
            ,deptId:undefined
            ,userName:undefined
            ,phone:undefined
            ,status:undefined
        },
       //分配角色按钮显示或隐藏
        showRoleButton:true,
         //非多选禁用
        multiple:true,
        //非单选禁用
        single:true,
        //表格数据
        userTableList:[],
        //遮罩
        loading:false,
        //表格数据条数
        total:0,
        //选中的集合
        ids:[],
        //添加修改表单
        form:{},
        //打开弹出层
        open:false,
        //表单校验
        rules: {
        userName: [
          { required: true, message: '用户姓名不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '用户手机号不能为空', trigger: 'blur' }
        ]
      },



      }
    },
    //钩子
    created(){
      selectAllDept().then(res =>{
        this.deptOptions = res.data
      })
      this.getDataByType('sys_normal_disable').then(res=>{
        this.statusOptions = res.data
      })
      this.getDataByType('sys_user_sex').then(res=>{
        this.sexOptions = res.data
      })
      this.getDataByType('sys_user_level').then(res=>{
        this.userRankOptions = res.data
      })
      this.getDataByType('sys_school_type').then(res=>{
        this.campusOptions = res.data
      })
      this.getDataByType('sys_user_background').then(res=>{
        this.backgroundOptions = res.data
      })
      // 加载用户是否参与排班
      this.getDataByType('sys_yes_no').then(res => {
        this.schedulingFlagOptions = res.data
      })

       // 加载用户教室
      this.getDataByType('sys_school_class').then(res => {
        this.studentClassOptions = res.data
      })

       // 加载用户教室
      this.getDataByType('sys_school_reading').then(res => {
        this.readingStateOptions = res.data
      })
      
   
     
      this.getlistUserForPage()
    },
    methods:{
      getlistUserForPage(){
        this.loading = true
        listUserForPage(this.addDateRange(this.queryParams,this.dateRange)).then(res =>{
          this.userTableList = res.data
          this.total = res.total
          this.loading = false
        })
      },
      //表格多选框选中事件
      handleSelectionChange(selection){
          this.ids = selection.map(item =>item.userId)
          this.single  =  !(selection.length ==1)
          this.multiple = !(selection.length>0)
          if(selection.length === 0){
            this.showRoleButton=true
          }
          selection.map(item =>{
            if(item.userId === 1){
                  this.showRoleButton=false
            }else{
                  this.showRoleButton=true
            }
            })
      },
      //搜索
      handleQuery(){
        this.getlistUserForPage()
      },
      //重置
      resetQuery(){
        this.resetForm('queryForm')
        this.queryParams.pageNum =1
        this.queryParams.pageSize =10
        this.dateRange=[]
        this.getlistUserForPage()


      },
      //新增
      handleAdd(){
        this.title= "添加用户"
          this.reset()
          this.open = true
      },
      //修改
      handleUpdate(row){
        
        this.title= "修改用户"
        this.reset()
        let userId = row.userId === undefined? this.ids[0]:row.userId
        getUserById(userId).then(res =>{
          this.form = res.data
          this.open = true
        })

      },
      //删除
      handleDelete(row){
         let userIds = row.userId === undefined ? this.ids : row.userId
         this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           deleteUserByIds(userIds).then(res =>{
            this.msgSuccess("删除成功")
            this.getlistUserForPage()
        })
        }).catch(() => {
           this.msgInfo("取消删除")
            this.getlistUserForPage()
        });
       
       
      },
      //重置密码
      handleResetPwd(){
         this.$confirm('此操作将不可逆, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           resetPwd(this.ids).then(res =>{
            this.msgSuccess("重置成功")
            this.getlistUserForPage()
        })
        }).catch(() => {
           this.msgInfo("取消重置")
            this.getlistUserForPage()
        });
       

      },
      //分配角色
      handleSelectRole(row){
       
        this.title = "分配角色"
         let userId = row.userId===undefined?this.ids[0]:row.userId
         this.roleUserId = userId
         //方式1
      //    selectAllRoles().then(res =>{
      //      this.roleTableList = res.data
      //     getRoleIdsByUserId(userId).then(res2 =>{
      //         res2.data.map(item =>{
      //           this.$refs.roleListTable.toggleRowSelection(this.roleTableList[item-1], true)
      //         })
      //   })
      // })
      //方式2
          selectAllRoles().then(res =>{
           this.roleTableList = res.data
          getRoleIdsByUserId(userId).then(res2 =>{
             res2.data.map(item1 =>{
               this.roleTableList.map(item2 =>{
                 if (item2.roleId ===item1) {
                   this.$refs.roleListTable.toggleRowSelection(item2, true)
                 }
               })
             })
        })
      })
        this.selectRoleOpen = true
      },
      handleSizeChange(val){
        this.queryParams.pageSize = val
        this.getlistUserForPage()
      },
      handleCurrentChange(val){
        this.queryParams.pageNum = val
        this.getlistUserForPage()
      },
      //翻译部门
      deptFormatter(row){
         let arr = []
         this.deptOptions.map(item => {
          if(item.deptId ===row.deptId){
            arr.push(item.deptName)
          }
        })
        return arr.join('')
      },
      //翻译性别
      sexFormatter(row){
          return this.selectDictLabel(this.sexOptions,row.sex)
      },
      
      //翻译用户任职
      userRankFormatter(row){
         return this.selectDictLabel(this.userRankOptions,row.userRank)
      },
      campusFormatter(row){
         return this.selectDictLabel(this.campusOptions,row.campus)
      },
      //翻译用户背景
      backgroundFormatter(row){
         return this.selectDictLabel(this.backgroundOptions,row.background)
      },
      //翻译状态
      statusFormatter(row){
        return  this.selectDictLabel(this.statusOptions,row.status)
      },

       readingStateFormatter(row){
        return  this.selectDictLabel(this.readingStateOptions,row.readingState)
       },
       studentClassFormatter(row){
        return  this.selectDictLabel(this.studentClassOptions,row.studentClass)
       },
      //提交
      handleSubmit(){
      this.$refs['form'].validate((valid) => {
          if (valid) {
            if(this.form.userId === undefined){
              //添加
              addUser(this.form).then(res =>{
                this.msgSuccess("添加成功")
                this.getlistUserForPage()
                this.open = false
              })
            }else{
              //修改
              updateUser(this.form).then(res =>{
                this.msgSuccess("修改成功")
                this.getlistUserForPage()
                this.open = false
              })
            }
          } 
        });
      },
      //取消
      cancel(){
          this.open = false
      },
      // 重置表单
    reset() {
      this.resetForm('form')
      this.form = {
        userId: undefined,
        userName: undefined,
        phone: undefined,
        sex: '0',
        age: 0,
        status: '0',
        email: undefined,
        strong: undefined,
        honor: undefined,
        introduction: undefined,
        remark: undefined,
        schedulingFlag: '0'
      }
    },
    //分配角色选中触发事件
    handleRoleTableSelectionChange(selection){
        this.roleSelectionIds = selection.map(item => item.roleId)
        console.log(this.roleSelectionIds)
        console.log("被选中了")
    },
    //确定分配角色
    handleSaveRoleUserSubmit(){
      console.log(this.roleSelectionIds)
      saveUserRole(this.roleUserId,this.roleSelectionIds).then(res =>{
        this.msgSuccess("分配成功")
        this.selectRoleOpen = false
        this.$refs.roleListTable.clearSelection();
      })

    },
    //取消分配角色
    cancelRoleUser(){
      this.$refs.roleListTable.clearSelection();
      this.selectRoleOpen = false
    }
    },
    //监听器
    watch:{
      'dateRange':{
        handler(val,oldVal){
            this.queryParams.pageNum = 1
            this.getlistUserForPage()
        },
        deep:true  //深度监视
      },
      'queryParams.deptId':{
         handler(val,oldVal){
            this.queryParams.pageNum = 1
            this.getlistUserForPage()
        },
        deep:true  //深度监视
      },
      'queryParams.userName':{
         handler(val,oldVal){
            this.queryParams.pageNum = 1
            this.getlistUserForPage()
        },
        deep:true  //深度监视
      },
      'queryParams.phone':{
         handler(val,oldVal){
            this.queryParams.pageNum = 1
            this.getlistUserForPage()
        },
        deep:true  //深度监视
      },
      'queryParams.status':{
         handler(val,oldVal){
            this.queryParams.pageNum = 1
            this.getlistUserForPage()
        },
        deep:true  //深度监视
      }
    }

  
}
</script>
<style scoped>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
